package com.ybkj.o2o.zhuanxian.controller.res;

import com.ybkj.o2o.zhuanxian.common.*;
import com.ybkj.o2o.zhuanxian.service.CarService;
import com.google.common.base.Preconditions;
import com.ybkj.o2o.zhuanxian.common.chart.ChartDay;
import com.ybkj.o2o.zhuanxian.common.chart.ChartMonth;
import com.ybkj.o2o.zhuanxian.common.chart.ChartYear;
import com.ybkj.o2o.zhuanxian.common.config.DaijiaApi;
import com.ybkj.o2o.zhuanxian.common.error.Error;
import com.ybkj.o2o.zhuanxian.common.error.ErrorConstantV4;
import com.ybkj.o2o.zhuanxian.common.error.ResultTransport;
import com.ybkj.o2o.zhuanxian.entity.Car;
import com.ybkj.o2o.zhuanxian.entity.Line;
import com.ybkj.o2o.zhuanxian.entity.Orbit;
import com.ybkj.o2o.zhuanxian.entity.Order;
import com.ybkj.o2o.zhuanxian.entity.OrderMemo;
import com.ybkj.o2o.zhuanxian.entity.OrderReview;
import com.ybkj.o2o.zhuanxian.entity.OrderStatus;
import com.ybkj.o2o.zhuanxian.manager.CarManager;
import com.ybkj.o2o.zhuanxian.manager.LineManager;
import com.ybkj.o2o.zhuanxian.manager.OrderManager;
import com.ybkj.o2o.zhuanxian.manager.OrderMemoManager;
import com.ybkj.o2o.zhuanxian.manager.OrderOrbitManager;
import com.ybkj.o2o.zhuanxian.manager.OrderReviewManager;
import com.ybkj.o2o.zhuanxian.manager.OrderStatusManager;
import com.ybkj.o2o.zhuanxian.service.LineService;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.*;


@Controller
@RequestMapping("api/order")
public class OrderController {

  @Autowired
  private OrderManager orderManager;

  @Autowired
  private OrderMemoManager orderMemoManager;

  @Autowired
  private OrderReviewManager orderReviewManager;

  @Autowired
  private OrderStatusManager orderStatusManager;

  @Autowired
  private OrderOrbitManager orderOrbitManager;

  @Autowired
  private LineService lineService;

  @Autowired
  private CarManager carManager;

  @Autowired
  private LineManager lineManager;
  
  @Autowired
  private DaijiaApi daijiaApi;

  @Autowired
  private CarService carService;

  private RestTemplate restTemplate = new RestTemplate();

  private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
  /**
   * 创建订单 .
   *
   * @param passengerId         客户Id
   * @param passengerName       客户姓名
   * @param passengerPhone      客户电话
   * @param companyId           公司Id
   * @param companyName         公司名称
   * @param channelName         订单来源
   * @param startAddress        出发地址
   * @param startLat            预约地经度
   * @param startLng            预约地纬度
   * @param endAddress          目的地地址
   * @param endLat              目的地经度
   * @param endLng              目的地纬度
   * @param serverTime          服务时间
   * @param budgetPay           预估总价
   * @param prestartPrice       预估开始价格
   * @param premileagePrice     预估里程价格
   * @param prerunTimePrice     预估服务时间价格
   * @param pretravelTime       预估时间
   * @param premileage          预估里程
   * @param prePay              是否预付费
   */
  @RequestMapping(value = "create", method = RequestMethod.POST)
  @ResponseBody
  @Transactional(rollbackFor = Exception.class)
  public ResultTransport create(
      @RequestParam("orderType") Integer orderType,
      @RequestParam("passengerId") Long passengerId,
      @RequestParam("passengerName") String passengerName,
      @RequestParam("passengerPhone") String passengerPhone, 
      @RequestParam("lineId") Long lineId,
      @RequestParam(required = false, value = "lineName") String lineName,
      @RequestParam("companyId") Long companyId,
      @RequestParam("companyName") String companyName,
      @RequestParam("channelName") String channelName,
      @RequestParam("startAddress") String startAddress, 
      @RequestParam("startLat") Double startLat,
      @RequestParam("startLng") Double startLng, 
      @RequestParam(required = false, value = "endAddress") String endAddress,
      @RequestParam(required = false, value = "endLat") Double endLat, 
      @RequestParam(required = false, value = "endLng") Double endLng,
      @RequestParam("startTime") Long serverTime,
      @RequestParam("serverDeadTime") Integer serverDeadTime, 
      @RequestParam(required = false, value = "budgetPay") Double budgetPay, 
      @RequestParam(required = false, value = "preStartPrice") Double prestartPrice, 
      @RequestParam(required = false, value = "preMileagePrice") Double premileagePrice, 
      @RequestParam(required = false, value = "preRunTimePrice") Double prerunTimePrice, 
      @RequestParam(required = false, value = "preTravelTime") Integer pretravelTime, 
      @RequestParam(required = false, value = "preMileage") Double premileage,
      @RequestParam(required = false, value = "prePay") Boolean prePay, 
      @RequestParam(required = false, value = "couponId") Long couponId, 
      @RequestParam(required = false, value = "peopleNumber") Long peopleNumber, 
      @RequestParam(required = false, value = "operator") String operator,
      @RequestParam(required = false, value = "memo") String memo, 
      @RequestParam(required = false, value = "takeDeliveryName") String takeDeliveryName,
      @RequestParam(required = false, value = "takeDeliveryPhone") String takeDeliveryPhone, 
      @RequestParam(required = false, value = "showPhone") String showPhone,
      @RequestParam(required = false, value = "showName") String showName, 
      @RequestParam(required = false, value = "serverAddress") String serverAddress,
      @RequestParam(required = false, value = "system") Boolean system, 
      @RequestParam("appKey") String appKey) {

    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    
    if (Order.TYPE_BAOCHE.equals(orderType)) {
      if (peopleNumber == null) {
        return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
      }
    }
    
    try {

      List<Order> orders = new LinkedList<Order>();
      Date serverDate = new Date(serverTime);
      Line line = lineService.findById(lineId, appKey);
      if (Order.ORDER_TYPE_APP.equals(channelName) || Order.ORDER_TYPE_WEIXIN.equals(channelName) || Order.ORDER_TYPE_WEB.equals(channelName)) {
        
        if (StringUtils.isBlank(serverAddress)) {
          return ResultTransport.getErrorBy(new Error(ErrorConstantV4.PARAM_ERROR.getCode(), "系统地址为空"));
        }
        
        Long orderAmount=1L;
        if(Order.TYPE_BAOCHE.equals(orderType)){
          orderAmount=peopleNumber;
        }
        Long parallelOrderNumber  = daijiaApi.getParallelOrderNumber(serverAddress,passengerId);
        Long count = orderManager.queryRunOrder(passengerId, appKey);
        
//        ResultTransport response = ResultTransport.getErrorBy(new Error(-1, "并行单量:"+parallelOrderNumber+",下单量:"+orderAmount+",当前单量:"+count));
//        return response;
        
        if (parallelOrderNumber>0 && count+orderAmount > parallelOrderNumber) {
          String message = "您当前有"+count+"个订单未结束!不能再下新单.";
          ResultTransport transport = ResultTransport.getErrorBy(new Error(ErrorConstantV4.ZHUAN_ORDER_TOOMACH.getCode(),message));
          Map<String,Object> map = new HashMap<String,Object>();
          map.put("number",count);
          transport.setData(map);
          return transport;
        }
        
        Integer countNotPayOrders = countNotPayOrders(serverAddress, passengerId);
        if (countNotPayOrders > 0) {
          return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOTPAY_ERROR);
        }
        
        Long todayAmounts = orderManager.countRunning(passengerId, appKey);
//        if (todayAmounts >= 10) {
//          return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_RUNNING_ERROR);
//        }
      }

      if (line == null) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ZHUANXIAN_LINE_NOT_EXISTS);
      }
      
      if (Order.TYPE_BAOCHE.equals(orderType)) {
        budgetPay = budgetPay / peopleNumber;
        for (int i = 0; i < peopleNumber; i++) {
          Order order = orderManager.insert(orderType, lineId, line.getName(),
                  line.getCompanyId(), line.getCompanyName(), passengerId,
                  passengerName, passengerPhone, channelName, startAddress,
                  startLat, startLng, endAddress, endLat, endLng, serverDate,
                  serverDeadTime, prestartPrice, premileagePrice, prerunTimePrice,
                  budgetPay, couponId, pretravelTime, premileage, peopleNumber,
                  operator, memo, takeDeliveryName, takeDeliveryPhone,
                  showPhone, showName, appKey, system);
          orders.add(order);
          couponId = null;
        }
      } else {
        Order order = orderManager.insert(
                orderType, lineId, line.getName(), line.getCompanyId(),
                line.getCompanyName(), passengerId, passengerName, passengerPhone,
                channelName, startAddress, startLat, startLng, endAddress,
                endLat, endLng, serverDate, serverDeadTime, prestartPrice, premileagePrice,
                prerunTimePrice, budgetPay, couponId, pretravelTime, premileage,
                peopleNumber, operator, memo, takeDeliveryName, takeDeliveryPhone,
                showPhone, showName, appKey, system);
        orders.add(order);
      }


      ResultTransport response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(orders);
      return response;
    } catch (Exception ex) {
      logger.error("create:{}",ex);
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }

//  @RequestMapping("test")
//  @ResponseBody
//  public String test(){
//    Double redPacket = new RandomRedPacket().redPacketProducer();
//    return redPacket.toString();
//  }

  /**
   * 司机补单 .
   * @param orderType           订单类型
   * @param passengerId         客户id
   * @param passengerName       客户名称
   * @param passengerPhone      客户电话
   * @param companyId           公司id
   * @param companyName         公司名称
   * @param channelName         来源
   * @param startAddress        预约地地址
   * @param startLat            预约地经度
   * @param startLng            预约地纬度
   * @param serverTime          服务时间
   * @param endAddress          目的地地址
   * @param endLat              目的地经度
   * @param endLng              目的地纬度
   * @param employId            服务人员id
   * @param employName          服务人员名称
   * @param employPhone         服务人员电话
   * @param employCompanyId     服务人员所属公司id
   * @param employNo            服务人员工号
   * @param serverDeadTime      服务结束时间
   * @param budgetPay           预算费用
   * @param employPhoto         服务人员头像
   * @param employScore         服务人员评分
   * @param peopleNumber        人数
   * @param memo                备注
   * @param takeDeliveryName    收货人姓名
   * @param takeDeliveryPhone   收货人电话
   * @param systemAddress       系统地址
   * @param appKey              区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "addmore", method = RequestMethod.POST)
  @ResponseBody
  public ResultTransport addmore(
      @RequestParam("orderType") Integer orderType,
      @RequestParam("passengerId") Long passengerId,
      @RequestParam("passengerName") String passengerName,
      @RequestParam("passengerPhone") String passengerPhone,
      @RequestParam("companyId") Long companyId, 
      @RequestParam("companyName") String companyName,
      @RequestParam("channelName") String channelName,
      @RequestParam("startAddress") String startAddress,
      @RequestParam("startLat") Double startLat,
      @RequestParam("startLng") Double startLng, 
      @RequestParam("serverTime") Long serverTime,
      @RequestParam("endAddress") String endAddress, 
      @RequestParam("endLat") Double endLat,
      @RequestParam("endLng") Double endLng, 
      @RequestParam("employId") Long employId,
      @RequestParam("employName") String employName,
      @RequestParam("employPhone") String employPhone,
      @RequestParam("employCompanyId") Long employCompanyId,
      @RequestParam("employNo") String employNo,
      @RequestParam("serverDeadTime") Integer serverDeadTime, 
      @RequestParam(required = false, value = "budgetPay") Double budgetPay, 
      @RequestParam(required = false, value = "employPhoto") String employPhoto, 
      @RequestParam(required = false, value = "employScore") Double employScore,
      @RequestParam(required = false, value = "peopleNumber") Long peopleNumber,
      @RequestParam(required = false, value = "memo") String memo, 
      @RequestParam(required = false, value = "takeDeliveryName") String takeDeliveryName, 
      @RequestParam(required = false, value = "takeDeliveryPhone") String takeDeliveryPhone,
      @RequestParam("serviceAddress") String systemAddress, 
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      if (StringUtils.isBlank(systemAddress)) {
        response = ResultTransport.getErrorBy(
            new Error(ErrorConstantV4.PARAM_ERROR.getCode(), "系统地址为空"));
        return response;
      }
      Map<String, Object> driverBusy = getDriverBusy(systemAddress, employId);
      if (!(boolean) driverBusy.get("success")) {
        return ResultTransport.getErrorBy(new Error(
            ErrorConstantV4.ORDER_IS_ZHUANXIAN_ERROR.getCode(), 
            (String) driverBusy.get("message")));
      }

      Date serverDate = new Date(serverTime);

      Car car = carManager.findByEmploy(employId, appKey);
      if (null == car) {
        return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_HAS_NOT_CAR);
      }
      List<Order> orders = orderManager.findRunOrderByEmployId(employId, null, appKey);

      Order tempOrder = new Order();
      if (serverDeadTime != 0) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(serverDate);
        calendar.add(Calendar.MINUTE, -serverDeadTime);
        tempOrder.setServerDeadTime(calendar.getTime());
      }
      if (!tempOrder.isYuyue()) {
        if (Order.TYPE_PINCHE.equals(orderType)) {
          Long seats = orderManager.countSeats(employId, appKey);
          if (peopleNumber + seats > car.getRidepeopleNumber()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.CAS_HAS_NOMORE_SEATS);
          }
          boolean flag = false;
          for (Order temp : orders) {
            if (Order.TYPE_BAOCHE.equals(temp.getOrderType())) {
              flag = true;
              break;
            }
          }
          if (flag) {
            return ResultTransport.getErrorBy(new Error(ErrorConstantV4.ORDER_IS_ZHUANXIAN_ERROR
                .getCode(), "已有包车订单不能补拼车订单"));
          }
        } else if (Order.TYPE_BAOCHE.equals(orderType)) {

          boolean flag = false;
          for (Order temp : orders) {
            if (Order.TYPE_BAOCHE.equals(temp.getOrderType())
                || temp.getOrderType().equals(Order.TYPE_PINCHE)
                || temp.getOrderType().equals(Order.TYPE_JIHUO)) {
              flag = true;
              break;
            }
          }
          if (flag) {
            return ResultTransport.getErrorBy(new Error(ErrorConstantV4.ORDER_IS_ZHUANXIAN_ERROR
                .getCode(), "已有其他类型的城际专线订单不能再补包车订单"));
          }
        } else if (Order.TYPE_JIHUO.equals(orderType)) {
          boolean flag = false;
          for (Order temp : orders) {
            if (Order.ORDER_STATUS_ZHIXING.equals(temp.getStatus())) {
              flag = true;
              break;
            }
          }
          if (flag) {
            return ResultTransport
                .getErrorBy(ErrorConstantV4.ORDER_STARTEXECUTION_JIHUO_NOT_PAIDAN);
          }
          flag = false;
          for (Order temp : orders) {
            if (Order.TYPE_BAOCHE.equals(temp.getOrderType())) {
              flag = true;
              break;
            }
          }
          if (flag) {
            return ResultTransport.getErrorBy(new Error(ErrorConstantV4.ORDER_IS_ZHUANXIAN_ERROR
                .getCode(), "已有包车订单不能补寄货订单"));
          }
        }
      }


      /*
       * if(peopleNumber+seats>car.getRidepeopleNumber()){ return
       * ResultTransport.getErrorBy(ErrorConstantV4.CAS_HAS_NOMORE_SEATS); }
       */
      Map<String, Object> map = new HashMap<String, Object>();
      Order order =
          orderManager.addmore(orderType, passengerId, passengerName, passengerPhone, companyId,
              companyName, channelName, startAddress, startLat, startLng, endAddress, endLat,
              endLng, serverDate, serverDeadTime, employId, employName, employPhone,
              employCompanyId, employNo, employPhoto, employScore, peopleNumber, memo, budgetPay,
              takeDeliveryName, takeDeliveryPhone, appKey);
      map.put("id", order.getId());
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(order.getId());
    } catch (Exception ex) {
      logger.error("addmore:{}",ex);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;

  }

  
  /**
   * 多条件分页查询订单 .
   * @param companyId           公司id
   * @param companyName         公司名称
   * @param orderNo             订单号
   * @param employId            服务人员id
   * @param employName          服务人员名称
   * @param employPhone         服务人员电话
   * @param passengerId         客户id
   * @param passengerName       客户名称
   * @param passengerPhone      客户电话
   * @param carNumber           车牌号
   * @param allorderType        全部订单类型
   * @param allstatus           状态
   * @param orderby             排序
   * @param page                页数(从1开始)
   * @param rows                每页数量
   * @param startTime           开始时间
   * @param endTime             结束时间
   * @param treatment           是否处理过
   * @param startFinishTime     开始服务时间
   * @param endFinishTime       结束服务时间
   * @param lineId              线路id
   * @param appKey              区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "findByParam", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport findByParams(
      @RequestParam(required = false, value = "companyId") Long companyId, 
      @RequestParam(required = false, value = "companyName") String companyName,
      @RequestParam(required = false, value = "orderNo") String orderNo, 
      @RequestParam(required = false, value = "employId") Long employId,
      @RequestParam(required = false, value = "employName") String employName, 
      @RequestParam(required = false, value = "employPhone") String employPhone, 
      @RequestParam(required = false, value = "passengerId") Long passengerId, 
      @RequestParam(required = false, value = "passengerName") String passengerName, 
      @RequestParam(required = false, value = "passengerPhone") String passengerPhone, 
      @RequestParam(required = false, value = "carNumber") String carNumber, 
      @RequestParam(required = false, value = "allorderType") String allorderType, 
      @RequestParam(required = false, value = "allstatus") String allstatus,
      @RequestParam(required = false, value = "orderby") String orderby, 
      @RequestParam(required = false, value = "page") Integer page, 
      @RequestParam(required = false, value = "rows") Integer rows,
      @RequestParam(required = false, value = "startTime") Long startTime, 
      @RequestParam(required = false, value = "endTime") Long endTime, 
      @RequestParam(required = false, value = "treatment") Boolean treatment, 
      @RequestParam(required = false, value = "startFinishTime") Long startFinishTime, 
      @RequestParam(required = false, value = "endFinishTime") Long endFinishTime, 
      @RequestParam(required = false, value = "lineId") Long lineId,
      @RequestParam("appKey") String appKey,@RequestParam(required = false, value = "lineIdStr") Long[] linesId) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      DataGrid<Order> dataGrid =
          orderManager.findByParam(startTime, endTime, companyId, companyName, orderNo,
              passengerId, passengerName, passengerPhone, employId, employName, employPhone,
              carNumber, orderby, allorderType, allstatus, page, rows, treatment, startFinishTime,
              endFinishTime, lineId, appKey, linesId);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(dataGrid);
    } catch (Exception ex) {
      logger.error("findByParam:{}",ex);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }
  
  
  /**
   * 查询某个人最后一个结算的订单 .
   * @param passengerId         客户id
   * @param appKey              区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = {"findLastOrder"}, method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport findLastOrder(
      @RequestParam("passengerId") Long passengerId,
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      Order order = orderManager.findLastOrder(passengerId, appKey);

      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(order);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }
  
  /**
   * 查询指定客户执行中的订单(状态0,1,2,3,4) .
   * @param passengerId     客户id
   * @param appKey          区分系统
   */
  @RequestMapping(value = {"queryRunOrder"}, method = RequestMethod.GET)
  public ResultTransport queryRunOrder(
      @RequestParam("passengerId") Long passengerId,
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      Long count = orderManager.queryRunOrder(passengerId, appKey);

      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(count);
    } catch (Exception ex) {
      logger.error("queryRunOrder:{}",ex);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;

  }

  /**
   * 后台查询单个订单 .
   * @param id      订单id
   * @param appKey  区分系统
   */
  @RequestMapping(value = "findOne", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport findOne(
      @RequestParam("orderId") Long id,
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    if (id == null) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      Order order = orderManager.findByIdAndAppKey(id, appKey);
      if (order != null) {
        List<OrderMemo> orderMemos = orderMemoManager.findByOrderId(id);
        order.setOrderMemos(orderMemos);
        OrderReview orderReview = orderReviewManager.findByOrderIdAndAppKey(id, appKey);
        order.setOrderReview(orderReview);
        List<OrderStatus> orderstatuslist = orderStatusManager.findByOrderId(id);
        order.setStatusList(orderstatuslist);
        Date end=new Date();
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(end);
        calendar.add(Calendar.MONTH, -6);
        Date start = calendar.getTime();
        
        Long count = orderManager.countFinishByPassenger(order.getPassengerId(), start, end, appKey, null);
        
        order.setCountNum(count);
        
      }
      
      
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(order);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }
  /**
   * 查询订单轨迹 .
   * @param orderId 订单id
   * @param appKey  区分系统
   */
  @RequestMapping(value = "findOrderOrbit", method = RequestMethod.GET)
  public ResultTransport findOrderOrbit(
      @RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    if (orderId == null) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      Orbit orbit = orderOrbitManager.findByOrderId(orderId);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(orbit);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }
  
  /**
   * 根据订单id查询拒单记录 .
   * @param orderId     订单id
   * @param appKey      区分系统
   */
  @RequestMapping(value = "findOrderRefuse", method = RequestMethod.GET)
  public ResultTransport findOrderRefuse(
      @RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    if (orderId == null) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      Order order = orderManager.findByIdAndAppKey(orderId, appKey);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(order);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }
  
  /**
   * 根据乘客id,完成时间段,查询订单数量 .
   * @param passengerId         客户id
   * @param startTime           开始时间
   * @param endTime             结束时间
   * @param orderFromSources    orderFromSources
   * @param appKey              区分系统
   */
  @RequestMapping(value = {"countFinishByPassenger"}, method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport countFinishByPassenger(
      @RequestParam("passengerId") Long passengerId,
      @RequestParam("startTime") Long startTime,
      @RequestParam(required = false, value = "endTime") Long endTime, 
      @RequestParam(required = false, value = "orderFromSources") String orderFromSources,
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      Long count = 0L;
      Date start = null;
      Date end = null;
      if (endTime != null) {
        end = new Date(endTime);
      }
      if (startTime != null) {
        start = new Date(startTime);
      }
      count =
          orderManager.countFinishByPassenger(passengerId, start, end, appKey, orderFromSources);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(count);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }

  /**
   * 确认订单结算信息 .
   *
   * @param orderId             订单Id
   * @param realPay             总金额
   * @param guoluMoney          过路金额
   * @param yuanchengMoney      远程金额
   * @param otherMoney          其它金额
   * @param startPrice          实际起步价
   * @param mileagePrice        实际的里程费
   * @param runTimePrice        实际的时间费用
   * @param endAddress          目的地(中途修改过的)
   * @param endLat              目的地纬度
   * @param endLng              目的地经度
   * @param mileage             实际里程
   * @param runTime             实际执行时间(分钟)
   * @param xml                 保单数据(暂无)
   */
  @RequestMapping(value = "confirmTask", method = RequestMethod.POST)
  @ResponseBody
  public ResultTransport completeTask(
      @RequestParam("orderId") Long orderId,
      @RequestParam("realPay") Double realPay,
      @RequestParam(required = false, value = "guoluMoney") Double guoluMoney,
      @RequestParam(required = false, value = "yuanchengMoney") Double yuanchengMoney,
      @RequestParam(required = false, value = "otherMoney") Double otherMoney,
      @RequestParam("startPrice") Double startPrice,
      @RequestParam("mileagePrice") Double mileagePrice,
      @RequestParam("runTimePrice") Double runTimePrice,
      @RequestParam(required = false, value = "waitTime") Integer waitTime,
      @RequestParam(required = false, value = "waitPrice") Double waitPrice, 
      @RequestParam(required = false, value = "endAddress") String endAddress,
      @RequestParam(required = false, value = "endLat") Double endLat, 
      @RequestParam(required = false, value = "endLng") Double endLng,
      @RequestParam("mileage") Double mileage, 
      @RequestParam("runTime") Integer runTime,
      @RequestParam(required = false, value = "xml") String xml,
      @RequestParam(required = false, value = "couponMoney") Double couponMoney,// 优惠券金额
      @RequestParam(required = false, value = "discount") Double discount, // 优惠券折扣
      @RequestParam(required = false, value = "prePayTypeDetail") String prePayTypeDetail, // 预支付类型
      @RequestParam(required = false, value = "memo") String memo,
      @RequestParam(required = false, value = "justKilometres") Double justKilometres,
      @RequestParam(required = false, value = "justMoney") BigDecimal justMoney,
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    Order order = null;

    try {
      orderManager.complete(orderId, realPay, guoluMoney, yuanchengMoney, otherMoney,
          startPrice, mileagePrice, runTimePrice,waitTime, waitPrice, endAddress, endLat, endLng,
          mileage, runTime, couponMoney, appKey, prePayTypeDetail, memo,justKilometres,justMoney);
      if (StringUtils.isNotBlank(xml)) {
        orderOrbitManager.insert(orderId, xml);
      } 
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(order);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }


  /**
   * 结算前准备接口.
   */
  @RequestMapping(value = "prepare", method = RequestMethod.POST)
  @ResponseBody
  public ResultTransport prepare(
          @RequestParam("orderId") Long orderId,
          @RequestParam("appKey") String appKey) {
    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    ResultTransport response = null;
    try {
      Boolean bool = false;
      bool = orderManager.prepare(orderId,appKey);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(bool);
      return response;
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
  }

  /**
   * 结算订单 .
   *
   * @param orderId             订单Id
   * @param afterPayTypeDetail  后支付类型
   * @param companyProfit       公司收入
   * @param employProfit        司机收入
   */

  @RequestMapping(value = "finishTask", method = RequestMethod.POST)
  @ResponseBody
  public ResultTransport finishTask(
      @RequestParam("orderId") Long orderId, 
      @RequestParam(required = false, value = "afterPayTypeDetail") String afterPayTypeDetail,
      @RequestParam("companyProfit") Double companyProfit,
      @RequestParam("employProfit") Double employProfit, 
      @RequestParam(required = false, value = "signMoney") Double signMoney, 
      @RequestParam(required = false, value = "balanceMoney") Double balanceMoney, 
      @RequestParam(required = false, value = "alipayMoney") Double alipayMoney,
      @RequestParam(required = false, value = "weixinMoney") Double weixinMoney, 
      @RequestParam(required = false, value = "unionpayMoney") Double unionpayMoney, 
      @RequestParam(required = false, value = "cashMoney") Double cashMoney, 
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    Order order = null;
    order =
        orderManager.finishTask(orderId, afterPayTypeDetail, companyProfit, employProfit,
            signMoney, balanceMoney, alipayMoney, weixinMoney, unionpayMoney,cashMoney, appKey);

    try {
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(order);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }
  
  /**
   * 推荐司机的时候判断可以派单的司机 .
   * @param orderType       订单类型
   * @param employId        服务人员id
   * @param peopleNumber    承载人数
   * @param appKey          区分系统
   */
  @RequestMapping(value = {"isReceiveAnOrder"}, method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport isReceiveAnOrder(
      @RequestParam("orderType") Integer orderType,
      @RequestParam("employId") Long employId, 
      @RequestParam(required = false, value = "peopleNumber") Long peopleNumber, 
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      boolean success = orderManager.isReceiveAnOrder(orderType, employId, peopleNumber, appKey);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(success);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;

  }

  /**
   * 催单更新催促时间 .
   * @param orderId     订单id
   * @param appKey      区分系统
   */
  @RequestMapping(value = {"hasten"}, method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport hastenOrder(
      @RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {

      Order order = orderManager.findByIdAndAppKey(orderId, appKey);
      if (order.getStatus() == 5 || order.getStatus() == 6) {
        response = ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        return response;
      }
      if (
          order.getLasturge() == null
              || (order.getLasturge() != null
              && (new Date().getTime() - order.getLasturge().getTime()) > (0.5 * 60 * 1000))) {

        order.setLasturge(new Date());
        orderManager.update(order);
      } else {
        response = ResultTransport.getErrorBy(ErrorConstantV4.YICUIGUO_NOTCUIDAN);
        return response;
      }

      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }

  /**
   * 关闭催促提示框 .
   * @param orderId     订单id
   * @param appKey      区分系统
   */
  @RequestMapping(value = {"closeHasten"}, method = RequestMethod.PUT)
  @ResponseBody
  public ResultTransport closeHasten(
      @RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {

      Order order = orderManager.findByIdAndAppKey(orderId, appKey);
      order.setIsClosed(true);
      orderManager.update(order);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(order);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }

  /**
   * 查询十个订单最早催促的订单,按催促时间顺序排序 .
   * @param appKey      区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = {"getHastenOrder"}, method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport getHastenOrder(
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      List<Order> list = orderManager.findHastenOrderAppKey(appKey);

      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(list);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }

  /**
   * zhuanxianDataForYear .
   * @param year        年份
   * @param companyId   公司id
   * @param appKey      区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = {"zhuanxianDataForYear"}, method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport zhuanxianDataForYear(
      @RequestParam("year") Integer year, 
      @RequestParam(required = false) Long companyId, 
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      ChartYear charYear = orderManager.dataForYear(year, companyId, appKey);

      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(charYear);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }
  
  /**
   * zhuanxianDataForMonth .
   * @param year        年份
   * @param companyId   公司id
   * @param month       月份
   * @param appKey      区分系统
   */
  @RequestMapping(value = {"zhuanxianDataForMonth"}, method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport zhuanxianDataForMonth(
      @RequestParam("year") Integer year, 
      @RequestParam(required = false) Long companyId, 
      @RequestParam(required = false) Integer month,
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      ChartMonth chartMonth = orderManager.dataForMonth(year, companyId, month, appKey);

      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(chartMonth);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }
  
  /**
   * zhuanxianDataForDay .
   * @param year        年
   * @param day         天
   * @param companyId   公司id
   * @param month       月
   * @param appKey      区分系统
   */
  @RequestMapping(value = {"zhuanxianDataForDay"}, method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport zhuanxianDataForDay(
      @RequestParam("year") Integer year,
      @RequestParam("day") Integer day,
      @RequestParam(value = "companyId", required = false) Long companyId, 
      @RequestParam(value = "month", required = false) Integer month, 
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      ChartDay chartDay = orderManager.dataForDay(year, month, day, companyId, appKey);

      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(chartDay);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }
  
  /**
   * zhuanxianEmployOrder .
   * @param start       开始时间
   * @param end         结束时间
   * @param employId    服务人员id
   * @param offset      页数(从1开始)
   * @param size        每页数量
   * @param appKey      区分系统
   */
  @RequestMapping(value = {"zhuanxianEmployOrder"}, method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport zhuanxianEmployOrder(
      @RequestParam("start") Date start,
      @RequestParam("end") Date end,
      @RequestParam(required = false, value = "employId") Long employId, 
      @RequestParam(required = false, value = "offset") Integer offset, 
      @RequestParam(required = false, value = "size") Integer size, 
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      Order order = orderManager.findFinishedByDriverWithDate(employId, start, end, appKey);

      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(order);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }
  
  
  /**
   * .
   * @param year   年
   * @param month  月
   * @param appKey appKey
   */
  @RequestMapping(value = {"zhuanxianHeatMap"}, method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport zhuanxianHeatMap(
      @RequestParam("year") Integer year,
      @RequestParam("month") Integer month, 
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      List<Order> order = orderManager.findMonthOrder(year, month, appKey);

      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(order);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }

  /**
   * .
   * @param companyId 公司id
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @param appKey    appKey
   */
  @RequestMapping(value = {"zhuanxianMemberOrder"}, method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport zhuanxianMemberOrder(
      @RequestParam(value = "companyId", required = false) Long companyId, 
      @RequestParam(required = false, value = "startTime") Long startTime, 
      @RequestParam(required = false, value = "endTime") Long endTime, 
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      Date startdate = null;
      Date enddate = null;
      if (startTime != null) {
        startdate = new Date(startTime);
      }
      if (endTime != null) {
        enddate = new Date(endTime);
      }

      PageVo<MemberOrderVo> order =
          orderManager.findMemberOrder(startdate, enddate, companyId, appKey);

      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(order);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }

  /**
   * .
   */
  @RequestMapping(value = "orderFromSource", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport orderFromSource(
      @RequestParam(required = false, value = "startDate") Long startDate, 
      @RequestParam(required = false, value = "endDate") Long endDate, 
      @RequestParam(required = false, value = "companyId") Long companyId, 
      @RequestParam("appKey") String appKey) {
    appKey = StringUtils.trimToEmpty(appKey);
    ResultTransport response = null;
    try {
      Date date1 = null;
      Date date2 = null;
      if (startDate != null) {
        date1 = new Date(startDate);
      }
      if (endDate != null) {
        date2 = new Date(endDate);
      }
      if (StringUtils.isBlank(appKey)) {
        return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
      }
      PageVo<OrderFromSourceVo> orderFromSources =
          orderManager.orderFromSource(date1, date2, companyId, appKey);

      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(orderFromSources);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }

  /**
   * .
   */
  @RequestMapping(value = "driverAchievement", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport driverAchievement(
      @RequestParam(value = "startDate", required = false) Long startDate, 
      @RequestParam(value = "endDate", required = false) Long endDate, 
      @RequestParam(value = "companyId",required = false) Long empCompanyId, 
      @RequestParam("appKey") String appKey) {
    appKey = StringUtils.trimToEmpty(appKey);
    ResultTransport response = null;
    try {
      Date date1 = null;
      Date date2 = null;
      if (startDate != null) {
        date1 = new Date(startDate);
      }
      if (endDate != null) {
        date2 = new Date(endDate);
      }
      if (StringUtils.isBlank(appKey)) {
        return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
      }
      PageVo<DriverOrderVo> orderFromSources =
          orderManager.driverAchievement(date1, date2, empCompanyId, appKey);

      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(orderFromSources);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;

  }

  /**
   * .
   */
  @RequestMapping(value = "companyOrder", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport companyOrder(
      @RequestParam(required = false, value = "startDate") Long startDate, 
      @RequestParam(required = false, value = "endDate") Long endDate, 
      @RequestParam("appKey") String appKey) {
    appKey = StringUtils.trimToEmpty(appKey);
    ResultTransport response = null;
    try {
      Date date1 = null;
      Date date2 = null;
      if (startDate != null) {
        date1 = new Date(startDate);
      }
      if (endDate != null) {
        date2 = new Date(endDate);
      }
      if (StringUtils.isBlank(appKey)) {
        return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
      }
      PageVo<CompanyOrderVo> orderFromSources = orderManager.companyOrder(date1, date2, appKey);

      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(orderFromSources);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }

  /**
   * .
   */
  @RequestMapping(value = "driverOrderDetailVo", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport driverOrderDetailVo(
      @RequestParam("driverId") Long driverId,
      @RequestParam(required = false, value = "startDate") Long startDate, 
      @RequestParam(required = false, value = "endDate") Long endDate, 
      @RequestParam(required = false, value = "page") Integer page,
      @RequestParam(required = false, value = "rows") Integer rows,
      @RequestParam("appKey") String appKey) {
    appKey = StringUtils.trimToEmpty(appKey);
    ResultTransport response = null;
    try {
      Date date1 = null;
      Date date2 = null;
      if (startDate != null) {
        date1 = new Date(startDate);
      }
      if (endDate != null) {
        date2 = new Date(endDate);
      }
      if (StringUtils.isBlank(appKey)) {
        return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
      }
      PageVo<DriverOrderDetailVo> driverDetailVo =
          orderManager.driverOrderDetailVo(driverId, date1, date2, page, rows, appKey);

      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(driverDetailVo);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }
  
  /**
   * 查询给司机指派的订单和执行中的订单(后台) .
   * @param employId    服务人员id
   * @param status      状态
   * @param appKey      区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = {"findMyWork"}, method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport findByWork(
      @RequestParam(required = false, value = "employId") Long employId, 
      @RequestParam(required = false, value = "status") String status, 
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      List<Order> orders = orderManager.findByWork(employId, appKey, status);

      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(orders);
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;

  }

  /**
   * 统计订单所有数据 .
   * @param companyId       公司Id
   * @param start           开始时间
   * @param end             结束时间
   * @param maincompany     是否是主公司
   * @param appKey          区分系统
   * @return 订单总金额, 单量, 公司收入, 司机收入 主公司加所有完成订单量,所有销单量,
   *     所有公司收入,所有司机收入,所有订单金额(realpay)
   */
  @RequestMapping(value = {"chart"}, method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport countAccount(
      @RequestParam(required = false, value = "companyId") Long companyId,
      @RequestParam(required = false, value = "start") Long start,
      @RequestParam(required = false, value = "end") Long end, 
      @RequestParam("maincompany") Boolean maincompany,
      @RequestParam(required = false, value = "lineId") Long lineId, 
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    Date startTime = null;
    Date endTime = null;
    if (null != start) {
      startTime = new Date(start);
    }
    if (null != end) {
      endTime = new Date(end);
    }
    try {
      Map<String, Object>  map = orderManager.chart(companyId, startTime, endTime,
          maincompany, lineId, appKey);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(map);
    } catch (Exception ex) {
      logger.error("chart:{}",ex);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }
  
  /**
   * 修改订单金额 .
   * @param orderId         订单id
   * @param couponMoney     优惠券抵消金额
   * @param cashMoney       现金
   * @param signMoney       签单金额
   * @param balanceMoney    余额金额
   * @param alipayMoney     支付宝支付金额     
   * @param weixinMoney     微信支付金额
   * @param operator        管理员
   * @param content         内容
   * @param appKey          区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "updateRealMoney", method = RequestMethod.POST)
  @ResponseBody
  public ResultTransport updateRealMoney(
      @RequestParam("orderId") Long orderId,
      @RequestParam("couponMoney") Double couponMoney, 
      @RequestParam("cashMoney") Double cashMoney,
      @RequestParam("signMoney") Double signMoney,
      @RequestParam("balanceMoney") Double balanceMoney,
      @RequestParam("alipayMoney") Double alipayMoney,
      @RequestParam("weixinMoney") Double weixinMoney, 
      @RequestParam("operator") String operator,
      @RequestParam("content") String content,
      @RequestParam("appKey") String appKey) {
    ResultTransport instance = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    Order order = orderManager.findByIdAndAppKey(orderId, appKey);
    if (order == null) {
      return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
    }
    try {
      orderManager.updateRealMoney(orderId, couponMoney, cashMoney, signMoney, balanceMoney,
          alipayMoney, weixinMoney, operator, content, appKey);

      instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      return instance;
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }
  
  /**
   * 查询某个服务人员的指定时间段的专车订单完成时间 .
   * @param employId    服务人员id
   * @param start       开始时间
   * @param end         结束时间
   * @param page        页数(从1开始)
   * @param rows        每页数量
   * @param appKey      区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "queryFinishOrderByEmployId", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport queryFinishOrderByEmployId(
      @RequestParam("employId") Long employId,
      @RequestParam(required = false, value = "start") Long start, 
      @RequestParam(required = false, value = "end") Long end, 
      @RequestParam("page") Integer page,
      @RequestParam("rows") Integer rows, 
      @RequestParam("appKey") String appKey) {
    ResultTransport instance = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      DataGrid<Order> dataGrid = new DataGrid<Order>();
      dataGrid = orderManager.queryFinishOrderByEmployId(employId, start, end, page, rows, appKey);

      instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      instance.setData(dataGrid);
      return instance;
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }

  /**
   * 查询单个乘客的未完成已确认的订单数量(后台的电话下单来源除外) .
   * @param passengerId     客户id
   * @param appKey          区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = {"countByPassengerId"}, method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport countByPassengerId(
      @RequestParam("passengerId") Long passengerId,
      @RequestParam("appKey") String appKey) {
    ResultTransport instance = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      Long number = orderManager.countByPassengerId(passengerId, appKey);

      instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      instance.setData(number);
      return instance;
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }
  
  /**
   * 查询客户当天下单数量包括新单,派单,销单,执行中(后台的电话下单来源除外) .
   * @param passengerId 客户id
   * @param appKey      区分系统
   */
  @RequestMapping(value = {"countRunning"}, method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport countRunning(
      @RequestParam("passengerId") Long passengerId,
      @RequestParam("appKey") String appKey) {
    ResultTransport instance = null;
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      Long number = orderManager.countRunning(passengerId, appKey);

      instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      instance.setData(number);
      return instance;
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }

  //-------------
  //华丽的分割线
  //-------------
  
  /**
   * 客户端查询单个订单 .
   * @param id      订单id
   * @param appKey  区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "findByOrderId", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport findByOrderId(
      @RequestParam("orderId") Long id,
      @RequestParam("appKey") String appKey) {
    if (StringUtils.isBlank(appKey) || null == id) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    Order order = orderManager.findByIdAndAppKey(id, appKey);
    System.out.println("randomRedPacket:"+order.getRandomRedPacket());
    if (null == order) {
      return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
    }

    try {
      Map<String, Object> map = new HashMap<String, Object>();
      Line line = lineManager.findById(order.getLineId(), appKey);
      map.put("orderId", order.getId());
      map.put("orderNumber", order.getOrderNo());
      map.put("orderNo", order.getOrderNo());
      map.put("time", order.getServerTime().getTime());
      map.put("serverTime", order.getServerTime().getTime());
      map.put("status", order.getStatus());
      map.put("startAddress", order.getStartAddress());
      map.put("startLng", order.getStartLng());
      map.put("startLat", order.getStartLat());
      map.put("endAddress", order.getEndAddress());
      map.put("endLng", order.getEndLng());
      map.put("endLat", order.getEndLat());
      map.put("fromPlace", order.getStartAddress());
      map.put("toPlace", order.getEndAddress());
      map.put("zxOrderType", order.getOrderType());
      map.put("passengerId", order.getPassengerId());
      map.put("passengerPhone", StringUtils.isNotBlank(order.getAnonymousNumber())?order.getAnonymousNumber():(StringUtils.isNotBlank(
          order.getShowPhone()) ? order.getShowPhone() : order.getPassengerPhone()));
      map.put("passengerName", StringUtils.isNotBlank(
          order.getShowName()) ? order.getShowName() : order.getPassengerName());
      map.put("companyAbbreviation", order.getCompanyName());
      map.put("companyId", order.getCompanyId());
      map.put("orderType", "zhuanxian");
      map.put("showPhone", order.getShowPhone());
      map.put("showName", order.getShowName());
      map.put("lineId", order.getLineId());
      map.put("budgetPay", order.getBudgetPay());
      map.put("carNumber", order.getCarNumber());
      map.put("carName", order.getCarName());
      map.put("lineName", order.getLineName());
      map.put("realPay", order.getRealPay());
      map.put("orderContent", 
          order.getOrderReview() != null ? order.getOrderReview().getContent() : null);
      map.put("orderScore", 
          order.getOrderReview() != null ? order.getOrderReview().getScore() : null);
      if (order.getEmployId() != null) {
        map.put("employId", order.getEmployId());
        map.put("employName", order.getEmployName());
        map.put("employPhoto", order.getEmployPhoto());
        map.put("employPhone", StringUtils.isNotBlank(order.getAnonymousNumber())?order.getAnonymousNumber():order.getEmployPhone());
        map.put("employNo", order.getEmployNo());
      }
      if (Order.TYPE_BAOCHE.equals(order.getOrderType())) {
        map.put("areaId", line.getBaocheAreaId());
      } else if (Order.TYPE_JIHUO.equals(order.getOrderType())) {
        map.put("areaId", line.getJihuoAreaId());
      } else if (Order.TYPE_PINCHE.equals(order.getOrderType())) {
        map.put("areaId", line.getAreaId());
      } else {
        map.put("areaId", null);
      }
      if (order.getTreatment()) {
        map.put("realCash",order.getRealPay());
        map.put("guoluMoney",order.getGuoluMoney());
        map.put("yuanchengMoney",order.getYuanchengMoney());
        map.put("otherMoney",order.getOtherMoney());
        map.put("mileage",order.getMileage());
        map.put("waitedTime",order.getStartWait());
        map.put("travelTime",order.getRunTime());
        map.put("startPrice",order.getStartPrice());
        map.put("mileagePrice",order.getMileagePrice());
        map.put("waitPrice",order.getWaitPrice());
        map.put("runTimePrice",order.getRunTimePrice());
        map.put("couponMoney",order.getCouponMoney());
      }
      map.put("treatment",order.getTreatment());
      map.put("randomRedPacket", null == order.getRandomRedPacket() ? 0.0 : order.getRandomRedPacket());
      List<OrderMemo> list = orderMemoManager.findByOrderId(order.getId());

      StringBuilder builder = new StringBuilder();

      if (list != null && list.size() != 0) {
        for (OrderMemo orderMemo : list) {
          builder.append(orderMemo.getMemo());
          builder.append(";");
        }
      }
      String memo = "";
      if (Order.TYPE_JIHUO.equals(order.getOrderType())) {
        memo =
            "收货人:(" + order.getTakeDeliveryName() + ") 、  收货人电话:(" + order.getTakeDeliveryPhone()
                + ")";
      }
      memo +=
          (((StringUtils.isNotBlank(order.getMemo())) ? order.getMemo() + ";" : "") + builder
              .toString());
      map.put("memo", memo);

      map.put("areaId", order.getAreaId());// App上面没有此属性

      List<OrderStatus> orderStatusList = orderStatusManager.findByOrderId(order.getId());
      for (OrderStatus os : orderStatusList) {
        if (os.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
          map.put("startdriveTime", os.getCreated().getTime());
        } else if (os.getStatus().equals(Order.ORDER_STATUS_ARRIVE)) {
          map.put("arriveTime", os.getCreated().getTime());
        } else if (os.getStatus().equals(Order.ORDER_STATUS_JIEDAN)) {
          map.put("acceptTime", os.getCreated().getTime());
        }

      }
      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      instance.setData(map);
      return instance;
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }
  
  /**
   * 根据城市查询所有线路(后台).
   * @param city    城市
   * @param appKey  区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "queryLine", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport queryType(
      @RequestParam("city") String city,
      @RequestParam("appKey") String appKey) {
    if (StringUtils.isBlank(appKey) || null == city) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      List<Line> list = lineService.findAll(city, appKey);
      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      /*
       * List<Map<String,Object>> mapData=new ArrayList<Map<String,Object>>(); if(list!=null &&
       * list.size()!=0){ for (Line line : list) { Map<String, Object> map = new HashMap<String,
       * Object>(); map.put("id",line.getId()); map.put("typeName",line.getName());
       * mapData.add(map); } }
       */
      instance.setData(list);
      return instance;
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }
  
  /**
   * 查询所有线路(客户端) .
   * @param city    城市
   * @param appKey  区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "queryLineAll", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport queryLineAll(
      @RequestParam(required = false, value = "city") String city,
      @RequestParam("appKey") String appKey) {
    if (StringUtils.isBlank(appKey) || null == city) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      List<Line> list = lineManager.queryLineAll(city, appKey);
      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

      instance.setData(list);
      return instance;
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }
  
  
  /**
   * 微信查询所有线路 .
   * @param lng     经度
   * @param lat     纬度
   * @param appKey  区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "wxQueryLineAll", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport wxQueryLineAll( 
      @RequestParam("lng") Double lng,
      @RequestParam("lat") Double lat,
      @RequestParam("appKey") String appKey) {
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      String city = HttpClientUtil.getCityByLngAndLat(lng, lat);
      List<Line> list = lineManager.queryLineAll(city, appKey);
      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

      instance.setData(list);
      return instance;
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }
  
  /**
   * 根据公司查询所有线路(客户端) .
   * @param companyId   公司id
   * @param city        城市
   * @param appKey      区分系统
   */
  @RequestMapping(value = "findLineByCompany", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport findLineByCompany(
      @RequestParam(required = false, value = "companyId") Long companyId, 
      @RequestParam(required = false, value = "city") String city, 
      @RequestParam("appKey") String appKey) {
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      List<Line> list = lineManager.findLineByCompany(companyId, city, appKey);
      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      List<Map<String, Object>> lineMap = new ArrayList<Map<String, Object>>();
      for (Line line : list) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("lineId", line.getId());
        map.put("companyId", line.getCompanyId());
        map.put("companyName", line.getCompanyName());
        map.put("pincheAreaId", line.getAreaId());
        map.put("jihuoAreaId", line.getJihuoAreaId());
        map.put("baocheAreaId", line.getBaocheAreaId());
        map.put("name", line.getName());
        map.put("startCity", StringUtils.isNotBlank(
            line.getStartCity()) ? line.getStartCity().split("-")[1] : "");
        map.put("startAddress", line.getStartAddress());
        map.put("endCity",StringUtils.isNotBlank(
            line.getEndCity()) ? line.getEndCity().split("-")[1] : "");
        map.put("endAddress", line.getEndAddress());
        map.put("appKey", line.getAppKey());

        List<Car> cars = carService.findByParam(line.getId(), line.getName(), line.getCompanyId(), line.getCompanyName(), null, null,
                new Integer[]{Car.CAR_FREE}, null, null, null, null, appKey);
        if(null!=cars) {
          List<Integer> peopleNumbers = new ArrayList<>();
          for (Car car : cars) {
            if(null!=car.getRidepeopleNumber()) {
              peopleNumbers.add(car.getRidepeopleNumber());
            }
          }
          if(cars.size()>1) {
            Collections.sort(peopleNumbers, new Comparator<Integer>() {
              public int compare(Integer o1, Integer o2) {
                return o2 - o1;
              }
            });
          }
          if(!peopleNumbers.isEmpty()) {
            map.put("peopleNumber", peopleNumbers.get(0));
          }
        }
        lineMap.add(map);
      }
      instance.setData(lineMap);
      return instance;
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }
  
  /**
   * 根据司机查询所有线路 .
   * @param employId    服务人员id
   * @param appKey      区分系统 
   * @return ResultTransport
   */
  @RequestMapping(value = "findLineByEmploy", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport findLineByEmploy(
      @RequestParam("employId") Long employId,
      @RequestParam("appKey") String appKey) {
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      List<Line> lines = lineManager.findLineByEmploy(employId, appKey);
      Line line = CollectionUtils.isEmpty(lines) ? null : lines.get(0);
      Map<String, Object> map = new HashMap<String, Object>();
      if (line != null) {
        map.put("id", line.getId());
        map.put("companyId", line.getCompanyId());
        map.put("companyName", line.getCompanyName());
        map.put("pincheAreaId", line.getAreaId());
        map.put("jihuoAreaId", line.getJihuoAreaId());
        map.put("baocheAreaId", line.getBaocheAreaId());
        map.put("name", line.getName());
        map.put("startCity", StringUtils.isNotBlank(
            line.getStartCity()) ? line.getStartCity().split("-")[1] : "");
        map.put("startAddress", line.getStartAddress());
        map.put("endCity",StringUtils.isNotBlank(
            line.getEndCity()) ? line.getEndCity().split("-")[1] : "");
        map.put("endAddress", line.getEndAddress());
        map.put("appKey", line.getAppKey());
        ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
        instance.setData(map);
        return instance;
      }
      return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_HAS_NOT_ZHUANXINA_LINE);
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }
  
  /**
   * 抢单 .
   * @param orderId             订单id
   * @param employId            服务人员id
   * @param employName          服务人员名称
   * @param employPhone         服务人员电话
   * @param employNo            服务人员工号
   * @param employScore         服务人员评分
   * @param employPhoto         服务人员头像
   * @param employCompanyId     服务人员所属公司id
   * @param appKey              区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = {"grab"}, method = RequestMethod.POST)
  @ResponseBody
  public synchronized ResultTransport grab(
      @RequestParam("orderId") Long orderId,
      @RequestParam("employId") Long employId, 
      @RequestParam("employName") String employName,
      @RequestParam("employPhone") String employPhone, 
      @RequestParam("employNo") String employNo,
      @RequestParam("employScore") Double employScore, 
      @RequestParam(required = false, value = "employPhoto") String employPhoto,
      @RequestParam("employCompanyId") Long employCompanyId, 
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    if (StringUtils.isBlank(appKey) || orderId == null || employId == null
        || StringUtils.isBlank(employName)) {
      response = ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
      return response;
    }
    try {
      Order order = orderManager.findByIdAndAppKey(orderId, appKey);
      if (order == null) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
      }
      if (order.getStatus() == 2 || order.getEmployId() != null) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_HASBEEN_RUSHED);
      }
      if (order.getStatus() == 6) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_HASBEEN_CANCEL);
      }
      Car car = carManager.findByEmploy(employId, appKey);
      if (car != null) {
        List<Line> lines = lineManager.findByCar(car.getId(), appKey);
        if (lines != null) {
          boolean flag = true;
          for (Line line : lines) {
            if (line.getId().equals(order.getLineId())) {
              flag = false;
              break;
            }
          }
          if (flag) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_HASBEEN_RUSHED);
          }
        }


      } else {
        return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_HAS_NOT_CAR);
      }
      order =
          orderManager.grab(orderId, employId, employName, employPhone, employNo, employScore,
              employPhoto, employCompanyId, appKey);
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("orderId", order.getId());
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(map);
      return response;
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }

  }
  
  /**
   * 派单 .
   * @param orderId         订单id
   * @param employId        服务人员id
   * @param employName      服务人员名称
   * @param employPhone     服务人员电话
   * @param employCompanyId 服务人员所属公司id
   * @param employNo        服务人员工号
   * @param employPhoto     服务人员头像
   * @param employScore     服务人员评分
   * @param operator        操作人
   * @param operatorMemo    操作人备注
   * @param appKey          区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "paidan", method = RequestMethod.POST)
  @ResponseBody
  public ResultTransport paidan(
      @RequestParam("orderId") Long orderId,
      @RequestParam("employId") Long employId, 
      @RequestParam("employName") String employName,
      @RequestParam("employPhone") String employPhone,
      @RequestParam("employCompanyId") Long employCompanyId,
      @RequestParam("employNo") String employNo,
      @RequestParam("employPhoto") String employPhoto,
      @RequestParam("employScore") Double employScore, 
      @RequestParam("operator") String operator,
      @RequestParam("operatorMemo") String operatorMemo, 
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    Order order = null;
    try {
      if (StringUtils.isBlank(appKey)) {
        return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
      }
      order = orderManager.findByIdAndAppKey(orderId, appKey);
      if (order == null) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
      }
      if (order.getStatus() != 0) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
      }
      if (employId == null) {
        return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
      }
      if (StringUtils.isBlank(employName)) {
        return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
      }
      if (StringUtils.isBlank(employPhone)) {
        return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
      }
      if (employCompanyId == null || employCompanyId == 0L) {
        return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
      }

      Car car = carManager.findByEmploy(employId, appKey);
      if (null == car) {
        return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_HAS_NOT_CAR);
      }
      List<Order> orders = orderManager.findRunOrderByEmployId(employId, null, appKey);
      if (!order.isYuyue()) {
        if (Order.TYPE_PINCHE.equals(order.getOrderType())) {
          Long seats = orderManager.countSeats(employId, appKey);
          if (order.getPeopleNumber() + seats > car.getRidepeopleNumber()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.CAS_HAS_NOMORE_SEATS);
          }
          boolean flag = false;
          for (Order temp : orders) {
            if (Order.TYPE_BAOCHE.equals(temp.getOrderType())) {
              flag = true;
              break;
            }
          }
          if (flag) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_EXISTING_BAOCHE_NOT_PAIDAN);
          }
        } else if (Order.TYPE_BAOCHE.equals(order.getOrderType())) {

          boolean flag = false;
          for (Order temp : orders) {
            if (Order.TYPE_BAOCHE.equals(temp.getOrderType())
                || temp.getOrderType().equals(Order.TYPE_PINCHE)
                || temp.getOrderType().equals(Order.TYPE_JIHUO)) {
              flag = true;
              break;
            }
          }
          if (flag) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_EXISTING_BAOCHE_NOT_PAIDAN);
          }
        } else if (Order.TYPE_JIHUO.equals(order.getOrderType())) {
          boolean flag = false;
          for (Order temp : orders) {
            if (Order.ORDER_STATUS_ZHIXING.equals(temp.getStatus())) {
              flag = true;
              break;
            }
          }
          if (flag) {
            return ResultTransport
                .getErrorBy(ErrorConstantV4.ORDER_STARTEXECUTION_JIHUO_NOT_PAIDAN);
          }
          flag = false;
          for (Order temp : orders) {
            if (Order.TYPE_BAOCHE.equals(temp.getOrderType())) {
              flag = true;
              break;
            }
          }
          if (flag) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_EXISTING_BAOCHE_NOT_PAIDAN);
          }
        }
      }
      orderManager.paidan(order, car, employId, employName, employPhone, employCompanyId, employNo,
          employPhoto, employScore, operator, operatorMemo, appKey);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      return response;
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
  }
  
  /**
   * 自动派单 .
   * @param orderId         订单id
   * @param employId        服务人员id
   * @param employName      服务人员名称
   * @param employPhone     服务人员电话
   * @param employCompanyId 服务人员所属公司id
   * @param employNo        服务人员工号
   * @param employPhoto     服务人员头像
   * @param employScore     服务人员评分
   * @param operator        操作者
   * @param operatorMemo    操作者备注
   * @param appKey          区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "autoPaidan", method = RequestMethod.POST)
  @ResponseBody
  public ResultTransport autoPaidan(
      @RequestParam("orderId") Long orderId,
      @RequestParam("employId") Long employId, 
      @RequestParam("employName") String employName,
      @RequestParam("employPhone") String employPhone,
      @RequestParam("employCompanyId") Long employCompanyId,
      @RequestParam("employNo") String employNo,
      @RequestParam("employPhoto") String employPhoto,
      @RequestParam("employScore") Double employScore, 
      @RequestParam("operator") String operator,
      @RequestParam("operatorMemo") String operatorMemo, 
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    Order order = null;
    try {
      if (StringUtils.isBlank(appKey)) {
        return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
      }
      order = orderManager.findByIdAndAppKey(orderId, appKey);
      if (order == null) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
      }
      if (order.getStatus() != 0) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
      }
      if (employId == null) {
        return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
      }
      if (StringUtils.isBlank(employName)) {
        return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
      }
      if (StringUtils.isBlank(employPhone)) {
        return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
      }
      if (employCompanyId == null || employCompanyId == 0L) {
        return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
      }

      Car car = carManager.findByEmploy(employId, appKey);
      if (null == car) {
        return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_HAS_NOT_CAR);
      }

      orderManager.paidan(order, car, employId, employName, employPhone, employCompanyId, employNo,
          employPhoto, employScore, operator, operatorMemo, appKey);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      return response;
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
  }

  /**
   * 收回订单 .
   * @param orderId     订单id
   * @param operator    操作人
   * @param cause       原因
   * @param appKey      区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "callback", method = RequestMethod.POST)
  @ResponseBody
  public ResultTransport callback(
      @RequestParam("orderId") Long orderId,
      @RequestParam("operator") String operator,
      @RequestParam(required = false, value = "cause") String cause,
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    Order order = null;
    try {
      if (StringUtils.isBlank(appKey)) {
        return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
      }
      order = orderManager.findByIdAndAppKey(orderId, appKey);
      if (order == null) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
      }
      if (order.getStatus() >= 4) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
      }
      orderManager.callback(orderId, operator, cause, appKey);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      return response;
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
  }
  
  /**
   * 司机端销单 .
   * @param orderId         订单id
   * @param employId        服务人员id
   * @param employName      服务人员名称
   * @param employPhone     服务人员电话
   * @param employCompanyId 服务人员所属公司id
   * @param employNo        服务人员工号
   * @param employPhoto     服务人员头像
   * @param employScore     服务人员评分
   * @param cause           原因
   * @param appKey          区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "employeCancel", method = RequestMethod.POST)
  @ResponseBody
  public ResultTransport employCancel(
      @RequestParam("orderId") Long orderId, 
      @RequestParam(required = false, value = "employId") Long employId, 
      @RequestParam(required = false, value = "employName") String employName,
      @RequestParam(required = false, value = "employPhone") String employPhone, 
      @RequestParam(required = false, value = "employCompanyId") Long employCompanyId, 
      @RequestParam(required = false, value = "employNo") String employNo,
      @RequestParam(required = false, value = "employPhoto") String employPhoto,
      @RequestParam(required = false, value = "employScore") Double employScore, 
      @RequestParam(required = false, value = "cause") String cause, 
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    Order order = null;
    try {
      if (StringUtils.isBlank(appKey)) {
        return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
      }
      order = orderManager.findByIdAndAppKey(orderId, appKey);
      if (order == null) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
      }
      if (order.getStatus().intValue() == 4) {
        return ResultTransport.getErrorBy(new Error(ErrorConstantV4.ORDER_STATUS_ERROR.getCode(),
            "订单已经开始执行,不能销单"));
      }
      if (order.getStatus().intValue() == 6) {
        return ResultTransport.getErrorBy(new Error(ErrorConstantV4.ORDER_STATUS_ERROR.getCode(),
            "该订单已经销单"));
      }
      if (!(order.getStatus().intValue() < 4)) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
      }
      if (StringUtils.isBlank(cause)) {
        return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
      }
      orderManager.employCancel(orderId, employId, employName, employPhone, employCompanyId,
          employNo, employPhoto, employScore, cause, appKey);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

      return response;
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
  }
  
  /**
   * 客户端销单 .
   * @param orderId         订单id
   * @param passengerId     客户id
   * @param passengerName   客户名称
   * @param passengerPhone  客户电话
   * @param cause           原因
   * @param appKey          区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "passengerCancel", method = RequestMethod.POST)
  @ResponseBody
  public ResultTransport passengerCancel(
      @RequestParam("orderId") Long orderId, 
      @RequestParam(required = false, value = "passengerId") Long passengerId, 
      @RequestParam(required = false, value = "passengerName") String passengerName,
      @RequestParam(required = false, value = "passengerPhone") String passengerPhone,
      @RequestParam(required = false, value = "cause") String cause,
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    Order order = null;
    try {
      if (StringUtils.isBlank(appKey)) {
        return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
      }
      order = orderManager.findByIdAndAppKey(orderId, appKey);
      if (order == null) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
      }
      if (order.getStatus().intValue() == 4) {
        return ResultTransport.getErrorBy(new Error(ErrorConstantV4.ORDER_STATUS_ERROR.getCode(),
            "订单已经开始执行,不能销单"));
      }
      if (order.getStatus().intValue() == 6) {
        return ResultTransport.getErrorBy(new Error(ErrorConstantV4.ORDER_STATUS_ERROR.getCode(),
            "该订单已经销单"));
      }
      if ((order.getStatus().intValue() > 4)) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
      }
      if (StringUtils.isBlank(cause)) {
        return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
      }
      orderManager.passengerCancel(orderId, passengerId, passengerName, passengerPhone, cause,
          appKey);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      return response;
    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
  }

  /**
   * 后台直接销单 .
   * 更新order对象-curd order,orderstatus
   * @param orderId     订单id
   * @param operator    操作人 
   * @param cause       原因
   * @param appKey      区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "cancel", method = RequestMethod.POST)
  @ResponseBody
  public ResultTransport updateStatus(
      @RequestParam("orderId") Long orderId,
      @RequestParam("operator") String operator, 
      @RequestParam("cause") String cause,
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    Order order = null;
    try {

      order = orderManager.findByIdAndAppKey(orderId, appKey);//已数据库为媒介更新order对象
      if (order == null) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
      }
      if (order.getStatus() >= Order.ORDER_STATUS_OK) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
      }
      orderManager.cancelOrder(orderId, operator, cause, appKey);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(order);
      return response;

    } catch (Exception ex) {
      ex.printStackTrace();
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
  }
  
  /**
   * 接单 .
   * @param orderId 订单id
   * @param appKey  区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "jiedan", method = RequestMethod.POST)
  @ResponseBody
  public ResultTransport jiedan(
      @RequestParam("orderId") Long orderId,
      @RequestParam("appKey") String appKey,@RequestParam(required = false, value = "serverUrl") String serverUrl) {
    if (StringUtils.isBlank(appKey) || null == orderId) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    Order order = orderManager.findByIdAndAppKey(orderId, appKey);

    if (null == order) {
      return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
    }
    if (!Order.ORDER_STATUS_PAIDAN.equals(order.getStatus())) {
      return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
    }
    Car car = carManager.findByEmploy(order.getEmployId(), appKey);
    if (null == car) {
      return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_HAS_NOT_CAR);
    }
    List<Order> orders = orderManager.findJiedanOrderByEmployId(order.getEmployId(), appKey);
    if (!order.isYuyue()) {
      if (Order.TYPE_PINCHE.equals(order.getOrderType())) {
        Long seats = orderManager.jiedanCountSeats(order.getEmployId(), appKey);
        if (order.getPeopleNumber() + seats > car.getRidepeopleNumber()) {
          return ResultTransport.getErrorBy(new Error(ErrorConstantV4.CAS_HAS_NOMORE_SEATS
              .getCode(), "已超出车辆可乘坐人数,不能接单"));
        }
        boolean flag = false;
        for (Order temp : orders) {
          if (Order.TYPE_BAOCHE.equals(temp.getOrderType())) {
            flag = true;
            break;
          }
        }
        if (flag) {
          return ResultTransport.getErrorBy(new Error(
              ErrorConstantV4.ORDER_EXISTING_BAOCHE_NOT_PAIDAN.getCode(), "已有其他类型订单不能再接单"));
        }
      } else if (Order.TYPE_BAOCHE.equals(order.getOrderType())) {

        boolean flag = false;
        for (Order temp : orders) {
          if (Order.TYPE_BAOCHE.equals(temp.getOrderType())
              || temp.getOrderType().equals(Order.TYPE_PINCHE)
              || temp.getOrderType().equals(Order.TYPE_JIHUO)) {
            flag = true;
            break;
          }
        }
        if (flag) {
          return ResultTransport.getErrorBy(new Error(
              ErrorConstantV4.ORDER_EXISTING_BAOCHE_NOT_PAIDAN.getCode(),
              "已有其他类型订单不能再接单"));
        }
      } else if (Order.TYPE_JIHUO.equals(order.getOrderType())) {
        boolean flag = false;
        for (Order temp : orders) {
          if (Order.ORDER_STATUS_ZHIXING.equals(temp.getStatus())) {
            flag = true;
            break;
          }
        }
        if (flag) {
          return ResultTransport
              .getErrorBy(new Error(
                  ErrorConstantV4.ORDER_STARTEXECUTION_JIHUO_NOT_PAIDAN.getCode(),
                  "已有寄货订单已经开始执行不能再接单"));
        }
        flag = false;
        for (Order temp : orders) {
          if (Order.TYPE_BAOCHE.equals(temp.getOrderType())) {
            flag = true;
            break;
          }
        }
        if (flag) {
          return ResultTransport.getErrorBy(new Error(
              ErrorConstantV4.ORDER_EXISTING_BAOCHE_NOT_PAIDAN.getCode(), "已有其他类型订单不能再接单"));
        }
      }
    }
    try {
      ResultTransport instance = null;
      Error error = orderManager.jiedan(orderId, appKey);
      if (error.getCode() == 0) {
        instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
        instance.setData(order);
      } else {
        instance = ResultTransport.getErrorBy(error);
      }

      return instance;
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }
  
  /**
   * 拒单 .
   * @param orderId     订单id
   * @param employId    服务人员id
   * @param cause       原因
   * @param operator    操作者
   * @param appKey      区分系统
   */
  @RequestMapping(value = "refuse", method = RequestMethod.POST)
  @ResponseBody
  public ResultTransport refuse(
      @RequestParam("orderId") Long orderId,
      @RequestParam("employId") Long employId,
      @RequestParam("cause") String cause,
      @RequestParam("operator") String operator, 
      @RequestParam("appKey") String appKey) {
    if (StringUtils.isBlank(appKey) || null == orderId || null == employId
        || StringUtils.isBlank(cause) || StringUtils.isBlank(operator)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    Order order = orderManager.findByIdAndAppKey(orderId, appKey);
    if (null == order) {
      return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
    }
    try {
      Error error = orderManager.refuse(orderId, employId, cause, operator, appKey);

      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      instance.setData(error);
      if (error.getCode() == 0) {
        instance.setData(order);
      }
      return instance;
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }
  
  /**
   * 到达预约地,开始等待 .
   * @param orderId     订单id
   * @param operator    操作者
   * @param appKey      区分系统
   */
  @RequestMapping(value = "wait", method = RequestMethod.POST)
  @ResponseBody
  public ResultTransport wait(
      @RequestParam("orderId") Long orderId,
      @RequestParam("operator") String operator, 
      @RequestParam("appKey") String appKey) {
    if (StringUtils.isBlank(appKey) || null == orderId || StringUtils.isBlank(operator)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    Order order = orderManager.findByIdAndAppKey(orderId, appKey);
    if (null == order) {
      return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
    }
    try {
      Error error = orderManager.wait(orderId, operator, appKey);
      ResultTransport instance = ResultTransport.getErrorBy(error);
      return instance;
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }

  /**
   * 开始执行订单 .
   * @param orderId     订单id
   * @param operator    操作者
   * @param appKey      区分系统 
   */
  @RequestMapping(value = "run", method = RequestMethod.POST)
  @ResponseBody
  @Transactional(rollbackFor = Exception.class)
  public ResultTransport run(
      @RequestParam("orderId") Long orderId,
      @RequestParam("operator") String operator, 
      @RequestParam("appKey") String appKey) {
    if (StringUtils.isBlank(appKey) || null == orderId || StringUtils.isBlank(operator)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    Order order = orderManager.findByIdAndAppKey(orderId, appKey);
    if (order == null) {
      return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
    }
    if (order.getStatus().equals(Order.ORDER_STATUS_JIEDAN)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
    }
    try {
      Error error = null;
      List<Order> orders = orderManager.findUnexecutedByEmployId(order.getEmployId(), appKey);
      if (!CollectionUtils.isEmpty(orders)) {
        for (Order o : orders) {
          error = orderManager.run(o.getId(), operator, appKey);
        }
      }
      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      instance.setData(error);
      return instance;
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }

  /**
   * 修改目的地 .
   * @param orderId     订单id
   * @param toPlace     地址
   * @param longitude   经度
   * @param latitude    纬度
   * @param appKey      区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "updateToPlace", method = RequestMethod.POST)
  @ResponseBody
  public ResultTransport updateToPlace(
      @RequestParam("orderId") Long orderId,
      @RequestParam("toPlace") String toPlace, 
      @RequestParam("longitude") Double longitude,
      @RequestParam("latitude") Double latitude, 
      @RequestParam("appKey") String appKey) {
    if (StringUtils.isBlank(appKey) || null == orderId) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    Order order = orderManager.findByIdAndAppKey(orderId, appKey);
    if (null == order) {
      return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
    }
    try {
      order.setEndAddress(toPlace);
      order.setEndLat(latitude);
      order.setEndLng(longitude);
      orderManager.update(order);
      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

      return instance;
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }
  
  /**
   * 根据服务人员查询完成的订单 .
   * @param employId    服务人员id
   * @param money       金额
   * @param appKey      区分系统
   * @param startTime   开始时间
   * @param endTime     结束时间
   * @return ResultTransport
   */
  @RequestMapping(value = "findOrderByEmployId", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport findOrderByEmployId(
      @RequestParam(required = true, value = "employId") Long employId,
      @RequestParam(required = true, value = "money") Double money, 
      @RequestParam(required = true, value = "appKey") String appKey,
      @RequestParam(required = false, value = "startTime") Long startTime, 
      @RequestParam(required = false, value = "endTime") Long endTime) {
    if (StringUtils.isBlank(appKey) || null == employId || money == null) {

      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      List<Order> list =
          orderManager.findOrderByEmployId(employId, money, appKey, startTime, endTime);

      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      instance.setData(list);
      return instance;
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }
  
  /**
   * 根据employId查询正在执行中的订单 .
   * @param employId    服务人员id
   * @param appKey      区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "findRunOrderByEmployId", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport findRunOrderByEmployId(
      @RequestParam("employId") Long employId,
      @RequestParam(required=false,value="treatment") Boolean treatment,
      @RequestParam("appKey") String appKey) {
    if (StringUtils.isBlank(appKey) || null == employId) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      List<Order> list = orderManager.findRunOrderByEmployId(employId, treatment, appKey);

      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      instance.setData(list);
      return instance;
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }

  /**
   * 报销 .
   * @param orderId         订单id
   * @param baoxiaoMoney    报销金额
   * @param appKey          区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "baoxiao", method = RequestMethod.POST)
  @ResponseBody
  public ResultTransport baoxiao(
      @RequestParam(required = true, value = "orderId") Long orderId,
      @RequestParam(required = true, value = "baoxiaoMoney") Double baoxiaoMoney, 
      @RequestParam(required = true, value = "appKey") String appKey) {
    if (StringUtils.isBlank(appKey) || orderId == null || baoxiaoMoney == null) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      Order order = orderManager.findByIdAndAppKey(orderId, appKey);
      if (null == order) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
      }
      orderManager.baoxiao(orderId, baoxiaoMoney, appKey);

      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

      return instance;
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }
  
  /**
   * 查询服务人员已用座位 .
   * @param employId    服务人员id
   * @param appKey      区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "countSeats", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport countSeats(
      @RequestParam(required = true, value = "employId") Long employId, 
      @RequestParam(required = true, value = "appKey") String appKey) {
    if (StringUtils.isBlank(appKey) || null == employId) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }

    try {

      Long seats = orderManager.countSeats(employId, appKey);

      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      instance.setData(seats);
      return instance;

    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }
  
  /**
   * 查询新单 .
   * @param companyId   公司id
   * @param appKey      区分系统
   * @return ResultTransport
   */
  @RequestMapping(value = "findNewOrder", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport findNewOrder(
      @RequestParam(required = false, value = "companyId") Long companyId, 
      @RequestParam(required = true, value = "appKey") String appKey) {

    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }

    try {
      List<Order> orders = orderManager.findNewOrder(companyId, appKey);

      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      instance.setData(orders);
      return instance;

    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }
  
  /**
   * 根据服务人员id，状态查询订单 .
   * @param employId 服务人员id
   * @param appKey   区分系统
   */
  @RequestMapping(value = "findActivedOrder", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport findActivedOrder(
      @RequestParam(required = true, value = "employId") Long employId, 
      @RequestParam(required = true, value = "appKey") String appKey) {

    if (StringUtils.isBlank(appKey) || null == employId) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }

    try {
      List<Order> orders = orderManager.findActivedOrder(employId, appKey);

      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      instance.setData(orders);
      return instance;

    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }

  /**
   * 根据线路id查询正在执行中的订单 .
   * @param lineId      线路id
   * @param appKey      区分系统
   */
  @RequestMapping(value = "findRunOrderByLineId", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport findRunOrderByLineId(
      @RequestParam(required = true, value = "lineId") Long lineId, 
      @RequestParam(required = true, value = "appKey") String appKey) {

    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }

    try {
      List<Order> order = orderManager.findRunOrderByLineId(lineId, appKey);

      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      instance.setData(order);
      return instance;

    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }

  /**
   * 根据车辆id查询正在执行中的订单 .
   * @param carId   车辆id
   * @param appKey  区分系统
   */
  @RequestMapping(value = "findRunOrderByCarId", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport findRunOrderByCarId(
      @RequestParam(required = true, value = "carId") Long carId, 
      @RequestParam(required = true,value = "appKey") String appKey) {

    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }

    try {
      List<Order> order = orderManager.findRunOrderByCarId(carId, appKey);

      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      instance.setData(order);
      return instance;

    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }

  /**
   * 客户端查询我的订单列表 .
   * @param passengerId     客户id
   * @param page            页数(从1开始)
   * @param rows            每页数量
   * @param appKey          区分系统
   */
  @RequestMapping(value = "findOrderByPassenger", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport findOrderByPassenger(
      @RequestParam(required = true, value = "passengerId") Long passengerId,
      @RequestParam(required = false, value = "page") Integer page, 
      @RequestParam(required = false, value = "rows") Integer rows,
      @RequestParam(required = true, value = "appKey") String appKey) {

    if (StringUtils.isBlank(appKey) || null == passengerId) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }

    try {
      DataGrid<Order> orders = orderManager.findOrderByPassenger(passengerId, page, rows, appKey);
      List<Map<String, Object>> listmap = new LinkedList<Map<String, Object>>();
      for (Order order : orders.getRows()) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orderId", order.getId());
        map.put("orderNo", order.getOrderNo());
        map.put("status", order.getStatus());
        map.put("passengerId", order.getPassengerId());
        map.put("startAddress", order.getStartAddress());
        map.put("startLng", order.getStartLng());
        map.put("startLat", order.getStartLat());
        map.put("employName", order.getEmployName());
        map.put("serverTime", order.getServerTime().getTime());
        map.put("employPhone", StringUtils.isNotBlank(order.getAnonymousNumber())?order.getAnonymousNumber():order.getEmployPhone());
        map.put("endAddress", order.getEndAddress());
        map.put("endLng", order.getEndLng());
        map.put("endLat", order.getEndLat());
        map.put("review", order.getReview());
        map.put("employId", order.getEmployId());
        map.put("employNo", order.getEmployNo());
        map.put("runTime", order.getRunTime());
        map.put("mileagePrice", order.getMileagePrice());
        map.put("startPrice", order.getStartPrice());
        map.put("orderContent", order.getOrderReview() != null ? order.getOrderReview()
            .getContent() : null);
        map.put("employScore", order.getEmployScore());
        map.put("realPay", order.getRealPay());
        map.put("budgetPay", order.getBudgetPay());
        map.put("runTimePrice", order.getRunTimePrice());
        map.put("orderScore", order.getOrderReview() != null ? order.getOrderReview().getScore()
            : null);
        map.put("employPhoto", order.getEmployPhoto());
        map.put("treatment", order.getTreatment());
        map.put("mileage", order.getMileage());
        map.put("waitTime", order.getStartWait());
        map.put("waitPrice", order.getWaitPrice());
        map.put("type", 4);
        map.put("payDetail", order.getPayType());
        map.put("carNumber", order.getCarNumber());
        map.put("zcOrderType", order.getOrderType());
        map.put("lineId", order.getLineId());
        map.put("lineName", order.getLineName());
        map.put("companyId", order.getCompanyId());
        map.put("companyAbbreviation", order.getCompanyName());
        map.put("memo", order.getMemo());
        listmap.add(map);
      }
      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      DataGrid<Map<String, Object>> dataMap = new DataGrid<Map<String, Object>>();
      dataMap.setRows(listmap);
      dataMap.setTotal(orders.getTotal());
      instance.setData(dataMap);
      return instance;

    } catch (Exception ex) {
      logger.error("findOrderByPassenger:{}",ex);
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }

  private Integer countNotPayOrders(String serverAddressp, Long passengerId) {
	  
	String serverAddress = serverAddressp;
    serverAddress = serverAddress.endsWith("/") ? serverAddress : serverAddress + "/";
    if(serverAddress.startsWith("http://") || serverAddress.startsWith("https://")){
    	serverAddress = (serverAddress.startsWith("http://") || serverAddress.startsWith("https://")) ? serverAddress : "https://" + serverAddress;
    }else{
      serverAddress = "https://" + serverAddress;
    }

    serverAddress = serverAddress + "api/passenger/v4/countNotPayOrders?passengerId={passengerId}";
    Map<String, String> map = new HashMap<String, String>();
    map.put("passengerId", passengerId + "");

    String result = restTemplate.getForObject(serverAddress, String.class, map);
    if (StringUtils.isNotBlank(result)) {
      JSONObject jo = new JSONObject(result);
      Integer code = jo.getInt("code");
      if (code == 0) {
        return jo.getInt("data");
      }
    }
    return 0;
  }
  
  private Map<String, Object> getDriverBusy(String serverAddress, Long employId) {

	serverAddress = serverAddress.endsWith("/") ? serverAddress : serverAddress + "/";
    if(serverAddress.startsWith("http://") || serverAddress.startsWith("https://")){
      serverAddress = (serverAddress.startsWith("http://") || serverAddress.startsWith("https://")) ? serverAddress : "https://" + serverAddress;
    }else{
      serverAddress = "http://" + serverAddress;
    }
	    
    serverAddress = serverAddress + "api/zhuanxian/getBuDanDriverBusy?employId={employId}";
    Map<String, String> map = new HashMap<String, String>();
    map.put("employId", employId + "");
    System.out.println("OrderController.getDriverBusy():" + serverAddress);
    String result = restTemplate.getForObject(serverAddress, String.class, map);
    Map<String, Object> resultMap = new HashMap<String, Object>();
    resultMap.put("success", false);
    resultMap.put("message", "当前服务人员不能补城际专线订单");
    if (StringUtils.isNotBlank(result)) {
      JSONObject jo = new JSONObject(result);
      Integer code = jo.getInt("code");
      if (code == 0) {
        resultMap.put("success", true);
        return resultMap;
      } else {
        resultMap.put("success", false);
        resultMap.put("message", jo.getString("message"));
      }
    }
    return resultMap;
  }

  /**
   * .
   */
  @RequestMapping(value = "driverOrderDetailCount", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport driverOrderDetailCount(
          @RequestParam("driverId") Long employId,
          @RequestParam(required = false, value = "startDate") Long start,
          @RequestParam(required = false, value = "endDate") Long end,
          @RequestParam("appKey") String appKey) {

    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    if (employId == null) {
      return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
    }
    Date startDate = null;
    Date endDate = null;
    if (start != null) {
      startDate = new Date(start);
    }
    if (end != null) {
      endDate = new Date(end);
    }
    try {

      Long num = orderManager.driverOrderDetailCount(employId,startDate,endDate,appKey);

      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      instance.setData(num);
      return instance;

    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }

  /**
   * .
   */
  @RequestMapping(value = "updateAnonymousNumber")
  @ResponseBody
  public ResultTransport updateAnonymousNumber(
          @RequestParam("orderId") Long orderId,
          @RequestParam(required = false,value = "anonymousNumber") String anonymousNumber,
          @RequestParam("appKey") String appKey) {
    try {
      orderManager.updateAnonymousNumber(orderId, anonymousNumber, appKey);

      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      return instance;

    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }


}
